<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	public function actionAbout(){
		$category = PostCategory::model()->with('posts')->findbyAttributes(array('title'	=>	'about'));
		$posts = $category->posts;
		$data['post'] = $posts[count($posts) - 1];

		$this->render('pages/about', $data);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				// Send email to admin
				$message = new YiiMailMessage;
				$message->view = 'contactus';
				$message->setBody(array('model'=>$model), 'text/html');
				$message->subject = 'Contact Us';
				$message->addTo(Yii::app()->params['adminEmail']);
				$message->from = Yii::app()->params['adminEmail'];
				Yii::app()->mail->send($message);

				// Success alert
				Yii::app()->user->setFlash('success','Contact form submitted! <br> <strong class="color-3">We will be in touch soon.</strong>');

				// Log contact to database
				$log_contact = new LogContact;
				$log_contact->name = $model->name;
				$log_contact->email = $model->email;
				$log_contact->message = $model->message;
				$log_contact->insert();

				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model = new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax'] === 'login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate())
            {
                if(!empty($returnUrl)){
                    $this->redirect(Yii::app()->createAbsoluteUrl($returnUrl));
                }
                if (strpos(Yii::app()->user->returnUrl,'/') === false)
                    $this->redirect(Yii::app()->user->returnUrl);
                $this->redirect(Yii::app()->homeUrl);
                // switch (Yii::app()->user->role_id){
                //     case ROLE_USER:
                //         $this->redirect(Yii::app()->homeUrl);
                //     break;
                //     case ROLE_ADMIN:
                //         $this->redirect(Yii::app()->createAbsoluteUrl('admin/site/login'));
                //     break;

                //     default :$this->redirect(Yii::app()->homeUrl);
                // }
                Yii::app()->end();
            }
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionRegister()
	{
		$model = new User('register');

        if(isset($_POST['User']))
        {
        	$model->attributes=$_POST['User'];
        	$model->validate();
            if(!$model->hasErrors())
            {
	            $model->first_name = $_POST['User']['first_name'];
	            $model->last_name = $_POST['User']['last_name'];
	            $model->email = $_POST['User']['email'];
                $model->status = STATUS_ACTIVE;
                $model->role_id = ROLE_MEMBER;
                if($model->save())
                {
                	$model->password = md5($_POST['User']['password']);
                	$model->update();
                	Yii::app()->user->setFlash('success', "Register successfully");
                }
            }
            else
            {
            	Yii::app()->user->setFlash('error', "Please fix some following errors: ");
            }
        }
     	$this->render('register', array('model' => $model));
	}

	public function actionAdvancedSearch()
	{
		$this->render('advancedsearch');
	}
//Display the list property page
	public function actionListProperty()
	{
		$result=$this->getLocations();
		$result1=$this->getInCondominuim();
		$result2=$this->getPropertyIsFor();
		$result3=$this->getTypeOfProperty();
		$result4=$this->getYouAreThe();
		$result5=$this->actionSave();
		$this->render('listproperty',array('loc'=>$result,'ic'=>$result1,'pif'=>$result2,'top'=>$result3,'yat'=>$result4,'model'=>$result5));
		//$this->render('listproperty');
	}

	public function getLocations()
	{
		$location = Location::model()->findAll();
		return $location;
	}

	public function getInCondominuim()
	{
		$incondominuim = InCondominuim::model()->findAll();
		return $incondominuim;
	}

	public function getPropertyIsFor()
	{
		$propertyisfor = PropertyIsFor::model()->findAll();
		return $propertyisfor;
	}

	public function getYouAreThe()
	{
		$youarethe = YouAreThe::model()->findAll();
		return $youarethe;
	}

	public function getTypeOfProperty()
	{
		$typeofproperty = TypeOfProperty::model()->findAll();
		return $typeofproperty;
	}

	public function actionSave()
	{
		$model=new Estate;
		$this->performAjaxValidation($model);
		if(isset($_POST['Estate']))
		{
			$model->attributes=$_POST['Estate'];
			if($model->save())
			{
				$model->update();
				$this->redirect('listproperty');
				Yii::app()->user->setFlash('success', "Your data has been successfully saved");
			}
			else
			{
				Yii::app()->user->setFlash('error', "Please fix some following errors: ");
			}
		}
		//$this->render('create',array('model'=>$model));
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='propertyform')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
//List property end
}